package tmall.security.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.Getter;
 import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import tmall.framework.utils.RedisTemplateUtil;
import tmall.security.utils.JwtTokenUtil;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private UserDetailsService userService;
    @Value("${jwt.header}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Getter
    private List<RequestMatcher> ignoreRequestMatchers = new ArrayList<>();
    @Value("${resource.ignoreUrl}")
    private void ignoreUrl(String ignoreUrl) {
        if (StringUtils.isNotEmpty(ignoreUrl)) {
            String[] urls = ignoreUrl.split(",");
            for (String url : urls) {
                ignoreRequestMatchers.add(new AntPathRequestMatcher(url, null));
            }
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = request.getHeader(tokenHeader);
        if (!StringUtils.isEmpty(authHeader) && authHeader.startsWith(tokenHead)) {
            String name = jwtTokenUtil.getUserNameFromToken(tokenHead);
            UserDetails userEObj = userService.loadUserByUsername(name);
            if (userEObj != null && jwtTokenUtil.validateToken(authHeader, userEObj)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEObj, null, null);
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
                String token = jwtTokenUtil.refreshHeadToken(authHeader);
                if (token != null && !token.equals(authHeader)) {
                    RedisTemplateUtil.set(token, userEObj.getUsername(),expiration);
                }
                response.setHeader(tokenHeader, token);
            }
        }
        doFilter(request, response, filterChain);
    }

}
